using UnityEngine;

public class LineMesh : MonoBehaviour
{
    private Vector3 startPoint;
    private Vector3 endPoint;
    private float lineWidth = 0.1f;
    
    private MeshFilter meshFilter;
    private MeshRenderer meshRenderer;
    private Mesh mesh;

    void Start()
    {
        // 添加必要的组件
        meshFilter = gameObject.AddComponent<MeshFilter>();
        meshRenderer = gameObject.AddComponent<MeshRenderer>();
        
        // 创建一个新的材质
        Material material = new Material(Shader.Find("Standard"));
        material.color = Color.red;
        meshRenderer.material = material;
        
        // 初始化mesh
        mesh = new Mesh();
        meshFilter.mesh = mesh;
    }

    public void SetPoints(Vector3 start, Vector3 end)
    {
        startPoint = start;
        endPoint = end;
        UpdateMesh();
    }

    private void UpdateMesh()
    {
        // 计算线段方向
        Vector3 direction = (endPoint - startPoint).normalized;
        Vector3 perpendicular = Vector3.Cross(direction, Camera.main.transform.forward).normalized;

        // 创建四个顶点
        Vector3[] vertices = new Vector3[4];
        vertices[0] = startPoint + perpendicular * lineWidth / 2;
        vertices[1] = startPoint - perpendicular * lineWidth / 2;
        vertices[2] = endPoint + perpendicular * lineWidth / 2;
        vertices[3] = endPoint - perpendicular * lineWidth / 2;

        // 定义UV坐标
        Vector2[] uv = new Vector2[4];
        uv[0] = new Vector2(0, 1);
        uv[1] = new Vector2(0, 0);
        uv[2] = new Vector2(1, 1);
        uv[3] = new Vector2(1, 0);

        // 定义三角形
        int[] triangles = new int[6];
        triangles[0] = 0;
        triangles[1] = 1;
        triangles[2] = 2;
        triangles[3] = 2;
        triangles[4] = 1;
        triangles[5] = 3;

        // 更新mesh
        mesh.Clear();
        mesh.vertices = vertices;
        mesh.uv = uv;
        mesh.triangles = triangles;
        
        // 重新计算法线
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
    }

    // 用于测试的方法
    void Update()
    {
        // 示例：连接原点和鼠标点击位置
        if (Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                SetPoints(transform.position, hit.point);
            }
        }
    }
}